package com.wthink.hzgj.station.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.home.data.Line
import com.wthink.hzgj.service.DevService
import com.wthink.hzgj.station.data.DefaultStationRepository
import com.wthink.hzgj.station.data.Station
import com.wthink.hzgj.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class StationViewModel : ViewModel() {

    private val repository = DefaultStationRepository()

    val stationList = MutableLiveData(emptyList<Station>())

    val current = MutableLiveData(Station("", ""))

    val upDir = MutableLiveData(true)
    val line = MutableLiveData(Line("", ""))

    fun start(lineId: String, lineName: String) {
        Log.debug("start at: ${System.currentTimeMillis()}")
        setLine(lineId, lineName)
        waitBusState()
    }

    fun select(station: Station) {
        val newStationList = stationList.value!!.map {
            Station(it.id, it.name, it.innerId, it.id.equals(station.id))
        }

        if (newStationList.isNotEmpty()) {
            newStationList.last().end = true
        }

        stationList.postValue(newStationList)
        current.postValue(station)
    }

    fun loadUpdir(updir: Boolean = true) {
        upDir.postValue(updir)
        viewModelScope.launch(Dispatchers.IO) {
            val start = System.currentTimeMillis()
            stationList.postValue(repository.getStationList(line.value!!.id, updir))
            Log.debug("load stationList use : ${System.currentTimeMillis() - start},post at: ${System.currentTimeMillis()}")
        }
    }

    private fun setLine(lineId: String, lineName: String) {
        if (line.value!!.id.equals(lineId)) {
            return
        }

        line.value = Line(lineId, lineName)
        stationList.value = emptyList()
        loadUpdir(upDir.value!!)
    }

    fun arrive() {
        if (current.value!!.id.isNotEmpty()) {
            viewModelScope.launch(Dispatchers.IO) {
                DevService.stationVoice(line.value!!.id, current.value!!.id, true)
            }
        }
    }

    fun leave() {
        if (current.value!!.id.isNotEmpty()) {
            viewModelScope.launch(Dispatchers.IO) {
                DevService.stationVoice(line.value!!.id, current.value!!.id, false)
            }
        }
    }

    fun waitBusState() {
        viewModelScope.launch(Dispatchers.IO) {
            DevService.listenBusState().collect {
                if (!line.value!!.id.equals(it.lineId) || upDir.value != it.upDir) {
                    line.postValue(Line(it.lineId, it.lineName))
                    stationList.postValue(repository.getStationList(line.value!!.id, it.upDir))
                }

                select(Station(it.stationId, it.stationName))
            }
        }
    }
}
